import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../views/Layout.vue'
import Login from '../views/login/Login.vue';

const routes = [
    // 登录

  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    redirect:'/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component:() => import('@/views/home/HomeView.vue'),
      },
      {
        // book功能
        path: 'book',
        name: 'book',
        component: () => import(/* webpackChunkName: "about" */ '../views/book/BookView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'addBook',
        name: 'AddBook',
        component: () => import(/* webpackChunkName: "about" */ '../views/book/AddBookView.vue'),
        meta: { requiresAuth: true }
      },
        // 借阅功能
      {
        path: 'borrow',
        name: 'borrow',
        component: () => import(/* webpackChunkName: "about" */ '../views/borrow/BorrowView.vue'),
        meta: { requiresAuth: true }
      },
        // 用户功能
      {
        path: 'user',
        name: 'user',
        component: () => import(/* webpackChunkName: "about" */ '../views/user/UserView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'addUser',
        name: 'AddUser',
        component: () => import(/* webpackChunkName: "about" */ '../views/user/AddUserView.vue'),
        meta: { requiresAuth: true }

      },
    ]
  },

  // {
  //   path: '/about',
  //   name: 'about',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  // }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = !!localStorage.getItem('loginId');
  if (to.matched.some(record => record.meta.requiresAuth) && !isLoggedIn) {
    next('/login');
  } else {
    next();
  }
});
export default router
